<template>
  <div class="page">
    <button @click="update">update</button>
    <div class="moon">
      <img src="./assets/月球.png" alt="" />
    </div>
    <div class="page-title">中秋采购清单</div>
    <div class="sub-tilte">Mid Autumn Festival</div>
    <NewInput class="mt_50" :addList="addList" />
    <ToDo
      class="mt_20"
      :list="list"
      :removeItem="removeItem"
      @change-checked="onChangeChecked"
    />
    <Footer
      class="mt_20"
      :list="list"
      :checkAll="checkAll"
      :clearPurchased="clearPurchased"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, watch } from 'vue'
import NewInput from './components/NewInput.vue'
import ToDo from './components/ToDo.vue'
import Footer from './components/Footer.vue'
import { Item } from './types/item'
import { saveList, getList } from './utils/index'

export default defineComponent({
  name: 'App',
  components: {
    NewInput,
    ToDo,
    Footer
  },
  setup() {
    let state = reactive<{ list: Item[] }>({
      list: getList()
    })
    const addList = (item: Item) => {
      state.list.unshift(item)
    }
    const removeItem = (id: number) => {
      const index = state.list.findIndex((item) => item.id === id)
      index !== -1 && state.list.splice(index, 1)
    }
    function onChangeChecked(item: Item, bool: boolean) {
      item.purchased = bool //哪个组件的数据就在哪个组件改
    }
    // 全选或取消全选
    function checkAll(isChecked: boolean) {
      state.list.forEach((item) => (item.purchased = isChecked))
    }
    // 清除已购买
    function clearPurchased() {
      state.list = state.list.filter((item) => !item.purchased)
    }
    // 缓存处理
    watch(
      () => state.list,
      saveList, // (val) => saveList(val)
      { deep: true }
    )
    return {
      ...toRefs(state),
      addList,
      removeItem,
      onChangeChecked,
      checkAll,
      clearPurchased
    }
  }
})
</script>

<style lang="scss">
* {
  box-sizing: border-box;
}
.page {
  min-height: 100vh;
  background-image: linear-gradient(to top, #ffecd2 0%, #fcb69f 100%);
  padding: 30px;
  width: 100vw;
  overflow: hidden;
}
.moon {
  width: 150px;
  height: 150px;
  position: absolute;
  top: -25px;
  right: 0;
  overflow: hidden;
  img {
    height: 100%;
    object-fit: cover;
  }
}
.page-title {
  padding: 20px 0 8px 20px;
  font-size: 24px;
  font-weight: bold;
  color: #fff;
}
.sub-tilte {
  padding-left: 20px;
  color: #fff;
}
.mt_50 {
  margin-top: 50px;
}
.mt_20 {
  margin-top: 20px;
}
</style>
